package com.example.finalcameraproject.controller;


import com.example.finalcameraproject.model.Camera;
import com.example.finalcameraproject.service.CameraService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class CameraController {

    @Autowired
    private CameraService cameraService;

    @GetMapping("/")
    public String viewHomePage(Model model) {
        return findPaginated(1, "cameraName", "asc",null,
                model);
    }

    @GetMapping("/showNewCameraForm")
    public String showNewCameraForm(Model model) {
        // create model attribute to bind form data
        Camera camera = new Camera();
        model.addAttribute("camera",camera);
        return "new_camera";
    }

    @PostMapping("/saveCamera")
    public String saveCamera(@ModelAttribute("camera") Camera camera) {
        // save Camera to database
        cameraService.saveCamera(camera);
        return "redirect:/";
    }

    @GetMapping("/showFormForUpdate/{id}")
    public String showFormForUpdate(@PathVariable(value = "id") long id, Model model) {


        Camera camera = cameraService.getCameraById(id);


        model.addAttribute("camera", camera);
        return "update_camera";
    }

    @GetMapping("/deleteCamera/{id}")
    public String deleteCamera(@PathVariable(value = "id") long id) {

        this.cameraService.deleteCameraById(id);
        return "redirect:/";
    }




    //获取分页数据
    @GetMapping("/page/{pageNo}")
    public String findPaginated(@PathVariable (value = "pageNo") int pageNo,
                                @RequestParam("sortField") String sortField,
                                @RequestParam("sortDir") String sortDir,
                                @RequestParam(required = false) String CameraState,
                                Model model) {
        int pageSize = 5;//

        Page<Camera> page = cameraService.findPaginated(pageNo, pageSize, sortField, sortDir, CameraState);
        List<Camera> listCamera = page.getContent();

        model.addAttribute("currentPage", pageNo);
        model.addAttribute("totalPages", page.getTotalPages());
        model.addAttribute("totalItems", page.getTotalElements());

        model.addAttribute("sortField", sortField);
        model.addAttribute("sortDir", sortDir);
        model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc");
        // 模糊查询，可以忽略大小写
        model.addAttribute("CameraState",CameraState);
        model.addAttribute("listCamera", listCamera);
        return "index";
    }
}
